package com.irrigation.controller;

import com.irrigation.dto.DeviceDto;
import com.irrigation.model.Device;
import com.irrigation.service.DeviceService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/devices")
@RequiredArgsConstructor
public class DeviceController {

    private final DeviceService deviceService;

    @GetMapping
    public ResponseEntity<List<DeviceDto>> getAllDevices() {
        return ResponseEntity.ok(deviceService.getAllDevicesDto());
    }

    @GetMapping("/{id}")
    public ResponseEntity<DeviceDto> getDevice(@PathVariable Long id) {
        return ResponseEntity.ok(deviceService.getDeviceById(id));
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<DeviceDto>> getDevicesByUserId(@PathVariable Long userId) {
        return ResponseEntity.ok(deviceService.getDevicesByUserId(userId));
    }

    @PostMapping
    public ResponseEntity<DeviceDto> createDevice(@RequestBody DeviceDto deviceDto) {
        return ResponseEntity.ok(deviceService.createDevice(deviceDto));
    }

    @PutMapping("/{id}")
    public ResponseEntity<DeviceDto> updateDevice(@PathVariable Long id, @RequestBody DeviceDto deviceDto) {
        return ResponseEntity.ok(deviceService.updateDevice(id, deviceDto));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteDevice(@PathVariable Long id) {
        deviceService.deleteDevice(id);
        return ResponseEntity.ok().build();
    }

    @PatchMapping("/{id}/status")
    public ResponseEntity<DeviceDto> updateDeviceStatus(
            @PathVariable Long id, 
            @RequestParam Device.DeviceStatus status) {
        return ResponseEntity.ok(deviceService.updateDeviceStatus(id, status));
    }

    @PostMapping("/{id}/control")
    public ResponseEntity<DeviceDto> controlDevice(@PathVariable Long id, @RequestBody DeviceControlRequest request) {
        deviceService.controlDevice(id, request.isAction());
        return ResponseEntity.ok(deviceService.getDeviceById(id));
    }
}

class DeviceControlRequest {
    private boolean action;

    public boolean isAction() {
        return action;
    }

    public void setAction(boolean action) {
        this.action = action;
    }
}
